package live.jipiao.dao;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import live.common.ErrorException;
import live.common.Format;
import live.common.ReadCodeName;
import live.jipiao.entity.AirData;
import live.jipiao.entity.AirQuery;
import live.jipiao.entity.CabinItem;
import live.jipiao.entity.FlightItem;

import org.dom4j.DocumentException;

import flight_pojo.FlightCabin;
import flight_pojo.FlightResponse;
import flight_services.GetFlightService;


public class QueryFlights {
	private AirData data = null;

	/**
	 * 返回查询结果
	 * 
	 * @param query
	 * @return
	 * @throws ErrorException
	 * @throws IOException
	 * @throws DocumentException
	 * @throws SQLException
	 */
	public AirData getFlights(AirQuery query) throws ErrorException,
			IOException, DocumentException, SQLException {
		GetFlightService gfs = new GetFlightService();
		List<FlightResponse> list = gfs.getFlightInfos(query.getFromCity(), query.getToCity(), query.getFromDate(), Format.getInstance().isNotNullOrEmpty(query.getCabinUsed())?query.getCabinUsed():"A");
		String errorCode = gfs.getErrorCode();
		if(errorCode==null){
			data = new AirData();
			FlightItem fi = null;
			List<FlightItem> flightList = new ArrayList<FlightItem>();
			for (FlightResponse item : list) {
				fi = new FlightItem();
				fi.setAircom(item.getBaseResponse().getAirLine());
				fi.setDepTime(Format.getInstance().stringToDate(item.getBaseResponse().getStime(),"HH:mm"));
				fi.setArrTime(Format.getInstance().stringToDate(item.getBaseResponse().getEtime(),"HH:mm"));
				fi.setModel(item.getBaseResponse().getFlightType());
				fi.setStop(item.getBaseResponse().getStop());
				fi.setFlightNo(item.getBaseResponse().getFlightNo());
				fi.setAircomName(ReadCodeName.aircomHashMap.get(item.getBaseResponse().getAirLine()).toString());
				fi.setTax(item.getBaseResponse().getTax());
				fi.setCabinList(getCabinList(item));
				fi.setDepAir(ReadCodeName.flightHashMap.get(item.getBaseResponse().getScityCode()).toString());
				fi.setArrAir(ReadCodeName.flightHashMap.get(item.getBaseResponse().getEcityCode()).toString());
				flightList.add(fi);
				fi = null;
			}
			data.setFlightList(flightList);
		}
		return data;
	}
	
	private List<CabinItem> getCabinList(FlightResponse item){
		List<CabinItem> cabinList = new ArrayList<CabinItem>();
		List<FlightCabin> cabins = item.getCabins();
		CabinItem cabin = null;
		for (FlightCabin flightCabin : cabins) {
			cabin = new CabinItem();
			cabin.setCode(flightCabin.getCabin());
			cabin.setDiscount(flightCabin.getRebate());
			cabin.setFare(String.valueOf(flightCabin.getPrice()));
			cabin.setRateId(flightCabin.getRateId());
			cabin.setSxf(flightCabin.getXf());
			cabin.setSeat(flightCabin.getNum().equals("A")?"9":flightCabin.getNum());
			cabinList.add(cabin);
			cabin = null;
		}
		return cabinList;
	}
	
}
